package com.jstyle.jclife.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.jstyle.jclife.R;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.ble.BleService;
import com.jstyle.jclife.model.BleData;
import com.jstyle.jclife.utils.ImageUtils;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.RxBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class GpsUpdateActivity extends Activity {
    private static final String TAG = "GpsUpdateActivity";


    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.iv_fileupdate_bg)
    ImageView ivFileupdateBg;
    @BindView(R.id.iv_gps_update_an)
    ImageView ivGpsUpdateAn;
    @BindView(R.id.tv_gps_update_tips1)
    TextView tvGpsUpdateTips1;
    @BindView(R.id.iv_update_circle)
    ImageView ivUpdateCircle;
    private Disposable subscription;


    private String binFileName = "cep_pak.bin";
    int maxLength = MainActivity.phoneDataLength;
    static final byte cmdCheck = (byte) 0x92;
    static final byte cmdSend = (byte) 0x93;
    private byte[] binByte;
    //private int[] binInt;
    private HashMap<Integer, byte[]> hashMap;
    private String downloadUrl = "http://www.le-young.com/files/1755/gps/cep_pak.bin";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps_update);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        ButterKnife.bind(this);
        // binFileName=getIntent().getStringExtra("gpsFile");
        Log.i(TAG, "onCreate: " + binFileName);
        init();
    }

    private void init() {
        ivGpsUpdateAn.setImageResource(R.drawable.anim_gps_update);
        AnimationDrawable animationDrawable = (AnimationDrawable) ivGpsUpdateAn.getDrawable();
        animationDrawable.start();
        AnimationDrawable animationDrawableUpdate = (AnimationDrawable) ivUpdateCircle.getDrawable();
        animationDrawableUpdate.start();
        subscription = RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BleData>() {
            @Override
            public void accept(BleData data) throws Exception {
                String action = data.getAction();
                if (BleService.ACTION_GATT_onDescriptorWrite.equals(action)) {
                    if(isSuccessful){
                        String info = getString(R.string.Gps_Update);
                        showUpdateStatus(info);
                    }
                } else if (BleService.ACTION_GATT_DISCONNECTED.equals(action)) {
//                    btConnect.setEnabled(true);
//                    btStartUpdate.setEnabled(false);
                    // dissMissDialog();
                } else if (BleService.ACTION_DATA_AVAILABLE.equals(action)) {
                    // Log.i(TAG, "accept: " + ResolveData.byte2Hex(data.getValue()));
                    resolveData(data.getValue());
                }
            }
        });
        initByteValue();
    }
    boolean isSuccessful;
    private void resolveData(byte[] value) {
        switch (value[0]) {
            case cmdCheck:
                if (value[1] == 1) {//查询是否需要升级
                    startData();
                } else if (value[1] == 2) {//升级数据发送完成
                    if (value[2] == 0) {//失败
                      //  info = getString(R.string.GPS_Updated_failed);
                    } else if (value[2] == 1) {//成功
                     //   info = getString(R.string.Gps_Update);
                        isSuccessful=true;
                    }
                } else if (value[1] == 3) {
                    Log.i(TAG, "resolveData: crc检测");
                } else if (value[1] == 0x10) {//超时
                    Log.i(TAG, "resolveData: 超时");
                }
                break;

            case cmdSend:
                if(hashMap==null)return;
                if (value[1] == 1) {
                    isFinish = false;
                    packageCount++;
                    sendData = hashMap.get(packageCount);
                    updateProgress();
                    if (sendData == null) {
                        endUpdateFile();
                    } else {
                        crcCount = ResolveData.CalcCRC16(sendData, sendData.length);
                        startData();
                    }

                } else if (value[1] == 0) {
                    Log.i(TAG, "resolveData: 重发" + packageCount);
                    isFinish = false;
                    sendData = hashMap.get(packageCount);
                    crcCount = ResolveData.CalcCRC16(sendData, sendData.length);
                    sendTotalPackage = sendTotalPackage - sendData.length;
                    startData();
                }
                break;
        }


    }

    long startTime;

    private void showUpdateStatus(String info) {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setMessage(info)
                .setCancelable(false)
                .setPositiveButton(getString(R.string.Confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .create();
        alertDialog.show();
    }

    private void updateProgress() {
        float send = sendTotalPackage;
        float total = binByte.length;
        float percent = send / total;
        NumberFormat format = NumberFormat.getPercentInstance();
        format.setMaximumFractionDigits(0);
        tvProgress.setText(format.format(percent));

    }

    int packageCount;
    int Count;
    int sendTotalPackage;//块发送长度
    int sendTotal;//总发送长度
    boolean isFinish;
    boolean isSendFinish;
    byte[] sendData;
    int crcCount;
    List<Integer> list;


    private void startData() {
        if (binByte.length==0||maxLength == 0 || isFinish) return;
        if (sendData == null) {
            endUpdateFile();
            return;
        }
        int dataLength = sendData.length;
        int contentLength = isFinish ? maxLength - 7 : maxLength - 5;
        isFinish = false;
        if (sendTotal + contentLength >= dataLength) {
            contentLength = dataLength - sendTotal;
            sendTotal = 0;
            isFinish = true;
        } else {
            sendTotal += contentLength;
        }
        if (sendTotalPackage + contentLength >= binByte.length) {
            contentLength = binByte.length - sendTotalPackage;
            isSendFinish = true;
        }
        int length = isFinish ? contentLength + 7 : contentLength + 5;
        byte[] value = new byte[length];
        value[0] = (byte) cmdSend;
        value[1] = (byte) packageCount;
        value[2] = (byte) Count++;
        System.arraycopy(binByte, sendTotalPackage, value, 3, contentLength);
        if (isFinish) {
            value[value.length - 4] = (byte) ((crcCount) & 0xff);
            value[value.length - 3] = (byte) ((crcCount >> 8) & 0xff);
        }
        int crc16 = ResolveData.CalcCRC16(value, value.length - 2);
        value[value.length - 2] = (byte) ((crc16) & 0xff);
        value[value.length - 1] = (byte) ((crc16 >> 8) & 0xff);
        sendTotalPackage += contentLength;
        //Log.i(TAG, "startUpDate: l " + sendTotalPackage);
        BleManager.getInstance().offerValue(value);
        if (isFinish) {
            Count = 0;
            BleManager.getInstance().offerValue((getEnd(packageCount, crcCount)));
            BleManager.getInstance().writeValue();
        } else {
            startData();
        }

    }

    private byte[] getEnd(int count, int crc) {
        byte[] value = new byte[7];
        value[0] = cmdSend;
        value[1] = (byte) count;
        value[2] = (byte) 0xff;
        value[3] = (byte) ((crc) & 0xff);
        value[4] = (byte) ((crc >> 8) & 0xff);
        int crc16 = ResolveData.CalcCRC16(value, value.length - 2);
        value[5] = (byte) ((crc16) & 0xff);
        value[6] = (byte) ((crc16 >> 8) & 0xff);
        return value;
    }
//    List<byte[]>valueList;
//    private void forUpdate(){
//        for(byte[]value:valueList){
//            int length=value.length;
//
//        }
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

//        if (BleManager.getInstance().isConnected())
//            BleManager.getInstance().disconnectDevice();
    }

    private void unsubscribe() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
            Log.i(TAG, "unSubscribe: ");
        }
    }


    private String loadFromSDFile(String fileName) {
        fileName = "/" + fileName;
        String result = null;
        try {
            File f = new File(Environment.getExternalStorageDirectory().getPath() + fileName);
            int length = (int) f.length();
            byte[] buff = new byte[length];
            FileInputStream fin = new FileInputStream(f);
            fin.read(buff);
            fin.close();
            result = new String(buff, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private byte[] readFile(File file) {
        // 需要读取的文件，参数是文件的路径名加文件名
        if (file.isFile()) {
            // 以字节流方法读取文件
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                // 设置一个，每次 装载信息的容器
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                // 开始读取数据
                int len = 0;// 每次读取到的数据的长度
                while ((len = fis.read(buffer)) != -1) {// len值为-1时，表示没有数据了
                    // append方法往sb对象里面添加数据
                    outputStream.write(buffer, 0, len);
                }
                // 输出字符串
                return outputStream.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件不存在！");
        }
        return null;
    }


    int[] crcList;

    private void initByteValue() {
        File binFile = new File(ImageUtils.UPDATEPATH + binFileName);
        binByte = readFile(binFile);
        int length = binByte.length % 4096 == 0 ? binByte.length / 4096 : binByte.length / 4096 + 1;
        crcList = new int[length];
        hashMap = new HashMap<>();
        Log.i(TAG, "initByteValue: " + length);
        for (int i = 0; i < length; i++) {
            int valueLength = 4096;
            if (i * 4096 + valueLength >= binByte.length) {
                valueLength = binByte.length - i * 4096;
            }
            byte[] value = new byte[valueLength];
            System.arraycopy(binByte, i * 4096, value, 0, valueLength);
            int crc = ResolveData.CalcCRC16(value, valueLength);
            crcList[i] = crc;
            hashMap.put(i, value);
        }
        sendData = hashMap.get(packageCount);
        crcCount = ResolveData.CalcCRC16(sendData, sendData.length);
        startTime = System.currentTimeMillis();
        //showProgressView(true);
        checkUpdateFile();
    }

    private void deleteFile() {
        byte[] value = new byte[4];
        value[0] = cmdCheck;
        value[1] = 0x70;
        int crc16 = ResolveData.CalcCRC16(value, 2);
        value[2] = (byte) ((crc16) & 0xff);
        value[3] = (byte) ((crc16 >> 8) & 0xff);
        BleManager.getInstance().writeValue(value);
    }

    private void checkUpdateFile() {
        File binFile = new File(ImageUtils.UPDATEPATH + binFileName);
        binByte = readFile(binFile);
        int length = binByte.length;
        int crc16 = ResolveData.CalcCRC16(binByte, binByte.length);
        byte[] value = new byte[42];//数据块最多16个，此数组长度固定（崩溃报告显示有超出16的）
        value[0] = cmdCheck;
        value[1] = 01;
        value[2] = (byte) ((length) & 0xff);//低位在前
        value[3] = (byte) ((length >> 8) & 0xff);
        value[4] = (byte) ((length >> 16) & 0xff);
        value[5] = (byte) ((length >> 24) & 0xff);
        value[6] = (byte) ((crc16) & 0xff);
        value[7] = (byte) ((crc16 >> 8) & 0xff);
        for (int i = 0; i < crcList.length; i++) {
            value[8 + i * 2] = (byte) ((crcList[i]) & 0xff);
            value[8 + i * 2 + 1] = (byte) ((crcList[i] >> 8) & 0xff);
        }
        int crcValue16 = ResolveData.CalcCRC16(value, value.length - 2);
        value[value.length - 2] = (byte) ((crcValue16) & 0xff);
        value[value.length - 1] = (byte) ((crcValue16 >> 8) & 0xff);
        BleManager.getInstance().writeValue(value);
    }

    private void endUpdateFile() {
//        File binFile = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "color565.bin");
//        byte[] binByte = readFile(binFile);
//        String md5String = loadFromSDFile(md5FileName);
//        byte[] binMd5 = getMd5Byte(md5String.trim());
        int length = binByte.length;
        int crc16 = ResolveData.CalcCRC16(binByte, binByte.length);
        byte[] value = new byte[10];
        value[0] = cmdCheck;
        value[1] = 02;
        value[2] = (byte) ((length) & 0xff);//低位在前
        value[3] = (byte) ((length >> 8) & 0xff);
        value[4] = (byte) ((length >> 16) & 0xff);
        value[5] = (byte) ((length >> 24) & 0xff);
        value[6] = (byte) ((crc16) & 0xff);
        value[7] = (byte) ((crc16 >> 8) & 0xff);
//        for(int i=0;i<crcList.length;i++){
//            value[8+i*2]=(byte) ((crcList[i]) & 0xff);
//            value[8+i*2+1]= (byte) ((crcList[i] >> 8) & 0xff);
//        }
        int crcValue16 = ResolveData.CalcCRC16(value, value.length - 2);
        value[value.length - 2] = (byte) ((crcValue16) & 0xff);
        value[value.length - 1] = (byte) ((crcValue16 >> 8) & 0xff);
        BleManager.getInstance().writeValue(value);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
